package com.car.servlet;

import com.car.service.UserService;
import com.car.entyti.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    UserService userService = new UserService();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        String acc = req.getParameter("account");
        String pwd = req.getParameter("password");

        User user = userService.login(acc, pwd);
        if (user != null) {
            req.getSession().setAttribute("msg", "登录成功");
            String token = UUID.randomUUID().toString();
            userService.setToken(user.getId(), token);

            Cookie cookie=new Cookie("TOKEN",token);
            cookie.setMaxAge(Integer.MAX_VALUE);
            cookie.setPath("/");
            resp.addCookie(cookie);
            resp.sendRedirect(req.getContextPath() + "/index.jsp");


        } else {

            req.getSession().setAttribute("msg", "登录失败");
            resp.sendRedirect(req.getContextPath() + "/login.jsp");

        }

    }


}
